package com.business.java2cache.util;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 */
public class ProReader {

    // 实例map
    private static Map<String, ProReader> instance = Collections
            .synchronizedMap(new HashMap<String, ProReader>());

    protected String sourceUrl;
    protected ResourceBundle resourceBundle;

    protected ProReader(String sourceUrl) {
        this.sourceUrl = sourceUrl;
        load();
    }


    public static ProReader getInstance(String sourceUrl) {
        sourceUrl = sourceUrl.replace(".properties", "");
        synchronized (ProReader.class) {
            ProReader manager = (ProReader) instance.get(sourceUrl);
            if (manager == null) {
                manager = new ProReader(sourceUrl);
                instance.put(sourceUrl, manager);
            }
            return manager;
        }
    }

    private synchronized void load() {
        try {
            resourceBundle = ResourceBundle.getBundle(sourceUrl);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("sourceUrl = " + sourceUrl + "file load error!", e);
        }
    }

    public String getProperty(String key) {
        try {
            return new String(resourceBundle.getString(key).getBytes("iso-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            return resourceBundle.getString(key);
        }
    }

    /**
     * 将文件中配置信息填充到properties对象中
     *
     * @return
     */
    public Properties fillProperties()
            throws MissingResourceException {
        Properties properties = new Properties();

        final ResourceBundle res = this.resourceBundle;
        Enumeration<String> en = res.getKeys();
        String key = null;
        String value = null;
        while (en.hasMoreElements()) {
            key = en.nextElement().trim();
            value = res.getString(key);
            properties.setProperty(key, value.trim());
        }
        return properties;
    }

}
